﻿using Furion.DependencyInjection;
using Microsoft.Extensions.Options;
using Vboot.Core.Framework;
using Vboot.Core.Module.Sys;

namespace Vboot.Web.Init;

//数据库初始化入口
public class DbInitListener : ITransient
{
    private readonly SysOrgInit _orgInit;
    private readonly SysPortalVbenInit _portalVbenInit;
    private readonly SysPortalVueInit _portalVueInit;
    private readonly SysApiInit _apiInit;
    private readonly AssInit _assInit;
    private readonly SqlSugarRepository<SysOrg> _sysOrgRepo;
    private readonly InitOptions _initOptions;

    public DbInitListener(SysOrgInit orgInit,
        SysPortalVbenInit portalVbenInit,
        SysPortalVueInit portalVueInit,
        AssInit assInit,
        SysApiInit apiInit,
        SqlSugarRepository<SysOrg> sysOrgRepo,
        IOptions<InitOptions> initOptions)
    {
        _orgInit = orgInit;
        _portalVbenInit = portalVbenInit;
        _portalVueInit = portalVueInit;
        _assInit = assInit;
        _apiInit = apiInit;
        _sysOrgRepo = sysOrgRepo;
        _initOptions = initOptions.Value;
    }

    //首次启动，数据库生成后，初始化组织架构，菜单，权限角色,接口等信息
    public async Task Init()
    {
        var sysOrg= _sysOrgRepo.GetSingle(it => it.id == "sa");
        if (sysOrg == null)
        {
            Console.WriteLine("首次启动系统，正在进行数据库初始化，请耐心等待。");
            await _orgInit.initRoot(_initOptions.OrgRootId,_initOptions.OrgName);       
            await _orgInit.InitSa();
            if (_initOptions.OrgType == "wc")
            {
                await _orgInit.initDept();
                await _orgInit.initTestOrg();
            }else if (_initOptions.OrgType == "test")
            {
                await _orgInit.initTestOrg();
            }
            Console.WriteLine("1 初始化部门与用户完毕");
            if (_initOptions.UiType == "vben")
            {
                await _portalVbenInit.initPortal();
                await _portalVbenInit.InitSysMenu();
                await _portalVbenInit.InitSaMenu();
            }
            else
            {
                await _portalVueInit.InitSysPortal();
                await _portalVueInit.InitSaPortal(); 
            }
            Console.WriteLine("2 初始化门户完毕");
            await _assInit.InitData();
            Console.WriteLine("3 初始化辅助数据完毕");
        }
        // await _portalVueInit.InitDcPortal();
        await _apiInit.Init();
    }

}